<?php

class CategoryController extends FController
{
    public function __construct($id,$module=null) {
        parent::__construct($id,$module);
        $this->menu=array(
            array('label'=>t('Manager Category','category'), 'url'=>array('/category/admin'),'linkOptions'=>array('class'=>'btn')),
            array('label'=>t('Create Category','category'), 'url'=>array('/category/create'),'linkOptions'=>array('class'=>'btn')),
        );
    }
    /*
     *  Actions
     * */
    public function actions() {
        return array(
            'autocomplete' => array(
                'class'=>'common.components.actions.AutoComplete',
                'model_class'=>'Category',
                'field'=>'name',
            )
        );
    }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];
            $parent_id = $_POST['Category']['parent_id'];
            if($parent_id == 0) {
                if($model->saveNode()) {
                user()->setFlash('success',t('<span class="label label-success">Success</span>  Category has been created successfully','category'));
                }
            } else {
            $root = Category::model()->findByPk($parent_id);
            if($model->appendTo($root)) {
               user()->setFlash('success',t('<span class="label label-success">Success</span>  Category has been created successfully','category'));
            }
            }

		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Category']))
		{
            $model->attributes=$_POST['Category'];
            $parent_id = $_POST['Category']['parent_id'];
            if($parent_id == 0 && !$model->isRoot()) {
                if($model->moveAsRoot()) {
                    user()->setFlash('success',t('<span class="label label-success">Success</span>  Category has been updated successfully','category'));
                    $model->saveNode();
                }
            } elseif($parent_id != 0) {
                if($parent_id == $model->id) {
                    user()->setFlash('warning',t('<span class="label label-warning">Warning</span>  The target parent should not be self','category'));
                } elseif (array_key_exists($parent_id,Category::getDescendants($model->id))) {
                    user()->setFlash('warning',t('<span class="label label-warning">Warning</span>  The target parent should not be descendant.','category'));
                }
                else {
                $parent = $this->loadModel($parent_id);
                if($model->moveAsLast($parent)) {
                    user()->setFlash('success',t('<span class="label label-success">Success</span>  Category has been updated successfully','category'));
                    $model->saveNode();
                }
              }
            }
		}

        $model->parent_id = $model->parent()->find();

        $model->meta_robots = str_replace(',',' |',$model->meta_robots);

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$category = $this->loadModel($id);
        $data = array();
        if($category->isLeaf()) {
            $content_in_category = Content::model()->count('category_id = :id',array(':id'=>$id));
            if($content_in_category > 0) {
                $data[$id]['status'] = false;
                $data[$id]['message'] = t('Delete category : <strong>{name}</strong> not successful, because this category contained {n} content(s)".','category',array('{name}'=>$category->name,'{n}'=>$content_in_category));
            }else {
                $category->deleteNode();
                $data[$id]['status'] = true;
                $data[$id]['message'] = t('Category : <strong>{name}</strong> has been deleted successfully','category',array('{name}'=>$category->name));
            }

        } else {
            $data[$id]['status'] = false;
            $data[$id]['message'] = t('Delete category : <strong>{name}</strong> not successful, because this category contained another category.','category',array('{name}'=>$category->name));
        }
        echo CJSON::encode($data);
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

    /**
     *  Batch Delete
     */
    public function actionBatchDelete() {
        $request = app()->request;
        if($request->isPostRequest) {
            $ids = explode(',',$request->getPost('ids'));
            $data = array();
            foreach($ids as $id) {
                $category = $this->loadModel($id);
                if($category->isLeaf()) {
                    $content_in_category = Content::model()->count('category_id = :id',array(':id'=>$id));
                    if($content_in_category > 0) {
                        $data[$id]['status'] = false;
                        $data[$id]['message'] = t('Delete category : <strong>{name}</strong> not successful, because this category contained {n} content(s)".','category',array('{name}'=>$category->name,'{n}'=>$content_in_category));
                    }else {
                        $category->deleteNode();
                        $data[$id]['status'] = true;
                        $data[$id]['message'] = t('Category : <strong>{name}</strong> has been deleted successfully','category',array('{name}'=>$category->name));
                    }

                } else {
                    $data[$id]['status'] = false;
                    $data[$id]['message'] = t('Delete category : <strong>{name}</strong> not successful, because this category contained another category.','category',array('{name}'=>$category->name));
                }
            }
            echo CJSON::encode($data);
        } else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model =  new Category('search');

        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Category']))
            $model->attributes=$_GET['Category'];
        $this->render('admin',array('model'=>$model));

	}
    public function actionChangeStatus($id) {
       $model = Category::model()->findByPk($id);
        if($model->is_active == 1) {
            $model->is_active = 0;
            $model->saveNode(false);
            $tooltip = t('Active','fcms');
        } else {
            $model->is_active = 1;
            $model->saveNode(false);
            $tooltip = t('Deactive','fcms');
        }
       $list = array(
         array(
             'id'=>$model->id,
             'name'=>$model->name,
             'url'=> url('/category/changeStatus/'.$model->id),
             'idhtml'=>'#status'.$model->id,
             'mes'=>t('Do you want to change status ?','category'),
             'status'=>$model->is_active,
             'token'=>'{ \''.app()->request->csrfTokenName .'\' : \''. csrfToken().'\' }',
             'rel'=>'tooltip',
             'tooltipTitle'=>$tooltip
         )
       );
       if(!$model->isLeaf()) {
           $des = $model->descendants()->findAll();
           foreach ($des as $de) {
               if($model->is_active == 1) {
                   $de->is_active = 1;
                   $de->saveNode(false);
                   $tooltip = t('Deactive','fcms');

               }else {
                   $de->is_active = 0;
                   $de->saveNode(false);
                   $tooltip = t('Active','fcms');
               }
               $list[] = array(
                   'id'=>$de->id,
                   'name'=>$de->name,
                   'url'=> url('/category/changeStatus/'.$de->id),
                   'idhtml'=>'#status'.$de->id,
                   'mes'=>t('Do you want to change status ?','category'),
                   'status'=>$de->is_active,
                   'token'=>'{ \''.app()->request->csrfTokenName .'\' : \''. csrfToken().'\' }',
                   'rel'=>'tooltip',
                   'tooltipTitle'=>$tooltip
               );
           }
       }
       header('Content-type:application/json');
       echo CJSON::encode($list);
    }
    public function actionRelational()
    {
        $id = Yii::app()->getRequest()->getParam('id');
        $model = Category::model()->findByPk($id);
        $this->renderPartial('_relational', array(
            'model'=>$model
        ));
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Category the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Category::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Category $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
